package my.util.single;

import my.util.AbstractList;

/**
 * <p>
 * 单链表-虚拟头节点
 * </p>
 *
 * @author AJun
 * @since 2020/8/12
 */
public class SingleLinkedListVirtualHead<E> extends AbstractList<E> {

    /**
     * 虚拟头节点
     */
    private Node<E> first;

    public SingleLinkedListVirtualHead() {
        first = new Node<>(null, null); // 空的虚拟头节点
    }

    /**
     * 节点
     */
    private static class Node<E> {
        E element; // 节点数据
        Node<E> next; // 指向下一个节点

        public Node(E element, Node<E> next) {
            this.element = element;
            this.next = next;
        }
    }

    @Override
    public int indexOf(E element) {
        Node<E> node = first.next;
        if (element == null) {
            for (int i = 0; i < size; i++) {
                if (node.element == null)
                    return i;
                node = node.next;
            }
        } else {
            for (int i = 0; i < size; i++) {
                if (element.equals(node.element))
                    return i;
                node = node.next;
            }
        }
        return -1;
    }

    @Override
    public E get(int index) {
        return node(index).element;
    }

    @Override
    public E set(int index, E element) {
        Node<E> node = node(index);
        E old = node.element;
        node.element = element;
        return old;
    }

    @Override
    public void add(int index, E element) {
        rangeCheckForAdd(index);

        // 如果 index == 0 则前一个节点就是虚拟头节点
        Node<E> prev = (index == 0 ? first : node(index - 1));
        prev.next = new Node<>(element, prev.next);
        size++;
    }

    @Override
    public E remove(int index) {
        rangeCheck(index);

        Node<E> prev = (index == 0 ? first : node(index - 1));
        Node<E> node = prev.next; // 要删除的节点
        prev.next = node.next; // 删除
        size--;
        return node.element;
    }

    @Override
    public void clean() {
        size = 0;
        first = null;
    }

    /**
     * 根据传入的索引返回该索引的元素
     */
    private Node<E> node(int index) {
        rangeCheck(index);

        Node<E> node = first.next;
        for (int i = 0; i < index; i++)
            node = node.next;
        return node;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("size=").append(size).append(", [");
        Node<E> node = first.next;
        for (int i = 0; i < size; i++) {
            if (i > 0) sb.append(", "); // 不需要减法运算
            sb.append(node.element);

            node = node.next;
        }
        sb.append("]");
        return sb.toString();
    }

}
